// three-utils.ts
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

export const initThreeScene = (container) => {
  const width = container.clientWidth;
  const height = container.clientHeight;

  // Set up scene, camera and renderer
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);
  container.appendChild(renderer.domElement);

  // Add lights
  const ambientLight = new THREE.AmbientLight(0x404040);
  scene.add(ambientLight);
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
  directionalLight.position.set(0, 1, 0);
  scene.add(directionalLight);

  // 创建格子地面
  const gridPlane = new THREE.GridHelper(10, 10); // 10x10的格子
  scene.add(gridPlane);

  // 创建OrbitControls
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true; // 启用阻尼效果
  controls.dampingFactor = 0.05; // 阻尼系数

  // Render loop
  const animate = () => {
    requestAnimationFrame(animate);
    controls.update(); // 更新控制器
    renderer.render(scene, camera);
  };
  animate();

  // 返回场景、相机、渲染器和控制器对象
  return { scene, camera, renderer, controls };
};